package com.itgone.manager.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.itgone.manager.annotation.ColumnTitle;
import com.itgone.manager.model.DataItem;
import com.itgone.manager.util.ExcelUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: earlman
 * @Description:
 * @Date:Create：in 2021-01-22 21:39
 */
@RestController
@RequestMapping("/index")
public class IndexController {

    @GetMapping("/say")
    public String sayHello() {
        return "hello world!";
    }

    @GetMapping("/login")
    public String login() {
        System.out.println("login1------");
        System.out.println(Thread.currentThread().getName());
        return "login";
    }

    @GetMapping("/login1")
    public String login1() {
        System.out.println("login1------");
        System.out.println(Thread.currentThread().getName());
        return "login";
    }

    @PostMapping(value = "/updateOrganization")
    public Object updateOrganization(@RequestBody Object obj) {
        System.out.println(JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue));
        return true;
    }

    @PostMapping(value = "/upload")
    public Object upload(MultipartFile file) throws IOException, IllegalAccessException {
        Workbook wb = ExcelUtil.openWorkbook(file.getInputStream());
        // 数值校验
        Resource resource = new ClassPathResource("VerificationJson.json");
        String verificationJson = FileUtils.readFileToString(new File(resource.getURI()));
        TypeReference<Map<String, List<String>>> typeReference = new TypeReference<Map<String, List<String>>>() {
        };
        Map<String, List<String>> stringListMap = JSON.parseObject(verificationJson, typeReference);

        List<DataItem> dataItemList = new ArrayList<>();
        for (Sheet sheet : wb) {
            String sheetName = sheet.getSheetName();
            if (!"data".equals(sheetName)) {
                continue;
            }
            List<String> titleList = null;
            for (Row row : sheet) {
                if (titleList == null) {
                    titleList = new ArrayList<>();
                    for (Cell cell : row) {
                        String cellValue = ExcelUtil.getCellValue(cell);
                        titleList.add(cellValue);
                    }
                    continue;
                }

                DataItem dataItem = new DataItem();
                for (Cell cell : row) {
                    int columnIndex = cell.getColumnIndex();
                    String title = titleList.get(columnIndex);
                    Field field = getFieldByColumnTitle(title);
                    if (field != null) {
                        String cellValue = ExcelUtil.getCellValue(cell);
                        if (stringListMap.containsKey(title)) {
                            List<String> strings = stringListMap.get(title);
                            if (!strings.contains(cellValue)) {
                                throw new RuntimeException("the value [" + cellValue + "] is illegal, column title is " + title);
                            }
                        }
                        field.setAccessible(true);
                        field.set(dataItem, cellValue);
                        field.setAccessible(false);
                    }
                }
                dataItemList.add(dataItem);
            }
        }
        return dataItemList;
    }

    private Field getFieldByColumnTitle(String title) {
        Field[] allFields = FieldUtils.getAllFields(DataItem.class);
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ColumnTitle.class)) {
                ColumnTitle annotation = field.getAnnotation(ColumnTitle.class);
                String value = annotation.value();
                if (value.equals(title)) {
                    return field;
                }
            }
        }
        return null;
    }
}
